package com.heima.search.listen;

import com.heima.common.constans.message.ArticleForEsConstants;
import com.heima.search.feign.ArticleFeign;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.kafka.annotation.KafkaListener;

import java.io.IOException;
import java.util.Map;

@ComponentScan
@Slf4j
public class ArticleAddOrRemoveListener {
    @Autowired
    ArticleFeign articleFeign;
    @Autowired
    ArticleSearchService articleSearchService;
    @KafkaListener(topics = ArticleForEsConstants.ARTICLE_ELASTICSEARCH_ADD)
    public void addArticle(String articleId){
        log.info("搜索微服务 接收到添加文章到索引库消息==>{}",articleId);
        Map article = articleFeign.findArticle(articleId);
        try {
            articleSearchService.saveArticle(articleId,article);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("索引库添加文章失败 文章id==> {}",articleId);
        }
    }

    public void removeArticle(String articleId){
        log.info("搜索微服务 接收到删除索引库文章消息 ==> {}",articleId);
        try {
            articleSearchService.deleteArticle(articleId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("索引库删除文章失败 文章id ==>",articleId);
        }
    }
}
